package com.example.bigevent.filter;

import com.example.bigevent.pojo.LoginUser;
import com.example.bigevent.pojo.User;
import com.example.bigevent.utils.JwtUtil;
import com.example.bigevent.utils.ThreadLocalUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Map;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        //自定义的过滤器 不会放行在security放行的请求，在这放行
        if(requestURI.contains("/user/login")||requestURI.contains("/user/register")||requestURI.contains("/user/captcha")){
            filterChain.doFilter(request,response);
            //过滤器再回来时直接return结束
            return;
        }
        try {
            String token = request.getHeader("Authorization");
            if(token==null){
                throw new RuntimeException();
            }
            Map<String, Object> map = JwtUtil.parseToken(token);
            //传来的token与redis存的不一样或redis的用户信息为空 就抛异常
            String s = stringRedisTemplate.opsForValue().get("big-event:token:user:" + map.get("id"));
            LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get("big-event:login:user:" + map.get("id"));
            if(!token.equals(s)||loginUser==null){
                throw new RuntimeException();
            }
            ThreadLocalUtil.set(map);
            UsernamePasswordAuthenticationToken authentication=new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request,response);
        } catch (RuntimeException e) {
            response.setStatus(401);
        }

    }
}
